import io
import json
import sys
import os
import os.path
import uuid
from docx import Document
from pathlib import Path

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', line_buffering=True)
sys.stdout.reconfigure(encoding='utf-8')


# ---------- 你的完整原始数据 ----------
def get_data():
    try:
        path = sys.argv[1]
        if os.path.exists(path):
            with open(path, "r", encoding="utf-8") as f:
                data = json.loads(f.read())   # 或 json.load(f)
        else:
            return {
                "status": False,
                "data": "路径不存在"
            }
    except IndexError:
        return {
            "status": False,
            "data": "没有参数路径"
        }
    return {
        "status": True,
        "data": data
    }

def main(data):
  doc = Document()
  file_name = f"{uuid.uuid4().hex}.docx"   # 32位16进制，无横线
  for idx, group in enumerate(data, 1):
      # doc.add_paragraph(f"第 {idx} 套")
      cols = len(group[0])
      rows = len(group)
      table = doc.add_table(rows=rows, cols=cols)
      for r, row_data in enumerate(group):
          for c, val in enumerate(row_data):
              table.cell(r, c).text = val
      doc.add_paragraph()  # 空一行

  path = os.path.join(Path(sys.argv[1]).resolve().parent,file_name)
  doc.save(path)
  return path

if __name__ == '__main__':
    arg = get_data()
    if arg["status"]:
        path = main(arg["data"])
        print(path,end="")
    else:
        print(arg["data"])